package com.tbit.uqbike.service.business.impl;

import com.alibaba.fastjson.JSON;
import com.aliyun.openservices.log.Client;
import com.aliyun.openservices.log.exception.LogException;
import com.aliyun.openservices.log.response.GetLogsResponse;
import com.tbit.common.config.OssDefaultConfig;
import com.tbit.uqbike.object.pojo.vo.ReturnBikeStatVO;
import com.tbit.uqbike.service.business.SLSLogService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @AUTHOR: wei.xing
 * @DATE: 2023-05-17 16:19
 **/
@Slf4j
@Data
@RefreshScope
@Service
public class SLSLogServiceImpl implements SLSLogService {

    @Resource
    private OssDefaultConfig ossDefaultConfig;

    private Client client;

    @PostConstruct
    public void init() {
        client = new Client(ossDefaultConfig.getSlsEndpoint(), ossDefaultConfig.getAccessKeyId(), ossDefaultConfig.getAccessKeySecret());
    }

    @Override
    public List<ReturnBikeStatVO> getNoReturnBikeStatList(Integer brandId, Integer accountId, Long startTime, Long endTime) {
        String querySql = "* | SELECT result as returnBikeType,count(*) as  returnBikeCount "
                + " WHERE accountId=" + brandId
                + " and adAccountId=" + accountId
                + " and result != 1 "
                + " GROUP BY result";
        String project = "tbit-client-test";
        List<String> list = execute(project, project, startTime, endTime, querySql);
        return list.stream()
                .map(v -> JSON.parseObject(v, ReturnBikeStatVO.class))
                .collect(Collectors.toList());
    }

    private List<String> execute(String project, String logStore, Long startTime, Long endTime, String querySql) {
        int from = (int) (startTime / 1000);
        int to = (int) (endTime / 1000);
        GetLogsResponse logsResponse;
        try {
            logsResponse = client.GetLogs(project, logStore, from, to, "", querySql, 0, 0, true);
            return logsResponse.getLogs().stream().map(log -> log.GetLogItem().ToJsonString()).collect(Collectors.toList());
        } catch (LogException e) {
            throw new RuntimeException(e);
        }
    }


}
